var chat = (function() {

	var user = {}

	var curSub = {}

	var friends = []

	var groups = []

	var msgCache = {};

	var params = {
		sub: 1,
		width: '40px',
		height: '40px',
		fontSize: '26px'
	};

	var init = function(options) {

		// 获取用户信息
		user = curUser;
		setUser();

		groups = [{
			"groupId": 1000000001,
			"groupName": "公共测试群组",
			"remark": null,
			"adminId": 2,
			"createGmt": null,
			"status": null,
			"groupIcon": null
		}];


		// 初始化会话列表
		initUserList()

		// 初始化联系人列表
		initFriendsList()


		// 接收socket消息
		socket.onmessage = function(event) {
			console.log(event)
			console.log(event.data)
			let data = event.data
			if (typeof data == 'string') {
				try {
					var msg = JSON.parse(data);
					if (typeof msg == 'object' && msg) {
						updateMessage(msg)
					}
				} catch (e) {
					console.log(e)
				}
			}
		};

	};


	function initUserList() {
		// 获取会话列表  .user_list
		ajax.get('chat/active-contacts', '', function(res) {
			let html = '';
			for (e of res.data) {
				let type = e.chatType
				for (msg of e.messageList) {
					updateMessage(msg)
				}

				let tpl =
					"<li data-id={{id}} data-conversation-id={{conversationId}} data-type={{chatType}} data-nickname={{nickname}} ><div><img src='{{avatar}}' /></div><span>{{nickname}}</span></li>"
				html = html + Mustache.render(tpl, {
					"id": e.id,
					"conversationId": e.conversationId,
					"chatType": e.chatType,
					"avatar": e.avatar,
					"nickname": e.name
				})

				if (curSub.conversationId == e.conversationId) {
					$('#chatbox').html('');
				}
			}
			$(".user_list").html(html)
		})

		// 会话列表点击样式/事件
		$(".user_list").on('click', 'li', function() {
			$(this).addClass();
			var id = $(this).data("id");
			var type = $(this).data("type");
			var nickname = $(this).data('nickname')
			var conversationId = $(this).data('conversation-id')
			console.log('id:' + id + ", type:" + type + ", conversationId:" + conversationId)
			$(this).siblings('li').removeClass('icon_active')
			$(this).addClass('icon_active')
			// 去除图标
			$(".bardge").hide();
			// 清屏
			$('#chatbox').html('');
			// 设置聊天对象名称
			$("#chat_subject").text(nickname);
			curSub = {
				"id": id,
				"conversationId": conversationId,
				"type": type,
				"nickname": nickname
			}
			// 初始化聊天记录
			var item = msgCache[conversationId];
			if (item != undefined) {
				item.forEach(function(msg) {
					setMsg(msg);
				})
			} else {
				// 拉取聊天记录
			}
		});
	}


	function initFriendsList() {
		// 获取联系人列表
		ajax.post('user/friends', {
			'pageNum': 0,
			'pageSize': 10
		}, function(res) {
			let html = '';
			friends = res.data.list
			for (e of friends) {
				let tpl =
					"<li data-id={{id}} data-conversation-id={{conversationId}} data-type={{chatType}} data-nickname={{nickname}} data-avatar={{avatar}} ><div><img src='{{avatar}}' /></div><span>{{nickname}}</span></li>"
				html = html + Mustache.render(tpl, {
					"id": e.id,
					"conversationId": e.conversationId,
					"chatType": 0,
					"avatar": e.avatar,
					"nickname": e.nickname
				})

				if (curSub.conversationId == e.conversationId) {
					$('#chatbox').html('');
				}
			}
			$(".friends_list").append(html)
		})

		// 获取群组列表
		ajax.post('group/my-groups', {
			'pageNum': 0,
			'pageSize': 10
		}, function(res) {
			let html = '';
			groups = res.data.list
			console.log(groups)
			for (e of groups) {
				let tpl =
					"<li data-id={{id}} data-conversation-id={{conversationId}} data-type={{chatType}} data-nickname={{nickname}} data-avatar={{avatar}} ><div><img src='{{avatar}}' /></div><span>{{nickname}}</span></li>"
				html = html + Mustache.render(tpl, {
					"id": e.id,
					"conversationId": e.id,
					"chatType": 1,
					"avatar": e.avatar,
					"nickname": e.name
				})

				if (curSub.conversationId == e.conversationId) {
					$('#chatbox').html('');
				}
			}
			$(".friends_list").append(html)
		})


		// 联系人点击样式/事件
		$(".friends_list").on('click', 'li', function() {
			$(this).addClass();
			var id = $(this).data("id");
			var type = $(this).data("type");
			var nickname = $(this).data('nickname')
			var avatar = $(this).data("avatar")
			var conversationId = $(this).data('conversation-id')
			console.log('id:' + id + ", type:" + type + ", conversationId:" + conversationId)
			$(this).siblings('li').removeClass('icon_active')
			$(this).addClass('icon_active')
			// 去除图标
			$(".bardge").hide();
			// 清屏
			$('#chatbox').html('');
			// 设置聊天对象名称
			$("#chat_subject").text(nickname);
			curSub = {
				"id": id,
				"conversationId": conversationId,
				"type": type,
				"nickname": nickname
			}
			// 先隐藏
			$(".user_list li[data-conversation-id='"+conversationId+"']").hide()
			// 添加
			let tpl =
				"<li data-id={{id}} data-conversation-id={{conversationId}} data-type={{chatType}} data-nickname={{nickname}} data-avatar={{avatar}}><div><img src='{{avatar}}' /></div><span>{{nickname}}</span></li>"
			let a = Mustache.render(tpl, {
				"id": id,
				"conversationId": conversationId,
				"chatType": type,
				"avatar": avatar,
				"nickname": nickname
			})
			$(".user_list").prepend(a)
			// 切换
			$("#si_1").trigger("click");
			console.log(conversationId)
			// 初始化聊天记录
			var item = msgCache[conversationId];
			if (item != undefined) {
				item.forEach(function(msg) {
					setMsg(msg);
				})
			} else {
				// 拉取聊天记录
			}
		});
	}


	var setUser = function() {
		$(".own_name").text(user.nickname);
		$("#own_avatar").html('<div class="own_avatar" data-sex="M" data-name="' + user.nickname + '">');
		$(".own_head").html('<div class="own_avatar" data-sex="M" data-name="' + user.nickname + '">');
		$(".own_avatar").avatarIcon(params);
		$(".own_numb").text("IM账号：" + user.id);
	}



	var time = function time(time) {
		// var date = new Date(time + 8 * 3600 * 1000); // 增加8小时
		// return date.toJSON().substr(0, 16).replace('T', ' ');
		return Date.parse(time).toLocaleString()
	}

	var updateMsgList = function(msg) {
		var tempList = [];
		for (var item in msgCache) {
			var list = msgCache[item];
			var latest = list[list.length - 1];
			tempList.push({
				id: latest.msgType == 2000 ? latest.from : latest.groupId,
				type: latest.msgType == 2000 ? 'friend' : 'group',
				name: latest.msgType == 2000 ? user.fmap[latest.from] : latest.groupName,
				content: latest.content,
				date: time(Number(latest.date))
			})
		}

		var tpl = "{{#msgs}}<li class=\"user_active\" data-id='{{id}}' data-type='{{type}}' >\n" +
			"                            <div class=\"avatar\" data-sex=\"M\" data-name=\"{{name}}\"></div>\n" +
			"                            <div class=\"user_text\">\n" +
			"                                <p class=\"user_name\">{{name}}</p>\n" +
			"                                <p class=\"user_message\">{{content}}</p>\n" +
			"                            </div>\n" +
			"                            <div class=\"user_time\">{{date}}</div>\n" +
			"                        </li>{{/msgs}}";

		var html = Mustache.render(tpl, {
			msgs: tempList
		});

		$(".user_list").html(html);
		$('.avatar').avatarIcon(params);
	}

	var updateMessage = function(msg) {
		setMsg(msg);
		cacheMsg(msg);
	}

	var setMsg = function(msg) {
		var chat = document.getElementById('chatbox');
		// msg.body = body = setFace(msg.body);
		if (msg.from == user.id) {
			chat.innerHTML += '<li class="me"><div class=\"me_avatar\" data-sex=\"M\" data-name=\"' + user
				.nickname + '\"></div><span>' + msg.title + '</span></li>';
			$("#chatbox .me_avatar").last().avatarIcon(params);
		} else {
			chat.innerHTML += '<li class="other"><div class=\"avatar\" data-sex=\"M\" data-name="' + msg
				.fromNickname + '"></div><span>' + msg.title + '</span></li>';
			$("#chatbox .avatar").last().avatarIcon(params);
		}
		var height = $("#chatbox").height();
		$('.office_text').animate({
			scrollTop: height
		}, 400);
	}

	var cacheMsg = function(msg) {
		// var type = msg.msgType == 2000 ? 'friend' : 'group';
		let conversationId = msg.conversationId
		var item = msgCache[conversationId];
		if (item != null) {
			item.push(msg)
		} else {
			msgCache[conversationId] = [msg];
		}
	}

	var sendMsg = function() {
		var text = document.getElementById('input_box');
		var chatbox = document.getElementById('chatbox');
		var talk = document.getElementById('talkbox');
		var content = encode(text.value);

		var msg = {
			'chatType': curSub.type,
			'msgType': 0,
			'from': user.id,
			'fromNickname': user.nickname,
			'to': curSub.id,
			'title': content
		};
		console.log(msg)
		socket.send(JSON.stringify(msg));
		cacheMsg(msg, msg.to);

		content = setFace(content);
		chatbox.innerHTML += '<li class="me"><div class=\"me_avatar\" data-sex=\"M\" data-name=\"' + user
			.nickname + '\"></div><span>' + content + '</span></li>';
		text.value = '';
		$("#chatbox .me_avatar").last().avatarIcon(params);
		talk.style.background = "#fff";
		text.style.background = "#fff";
		var height = $("#chatbox").height();
		$('.office_text').animate({
			scrollTop: height
		}, 400);
	}

	var encode = function(sHtml) {
		return sHtml.replace(/[<>&"]/g, function(c) {
			return {
				'<': '&lt;',
				'>': '&gt;',
				'&': '&amp;',
				'"': '&quot;'
			} [c];
		});
	}

	var setFace = function(content) {
		// var faces = content.match(/(?<=face\[).*?(?=\])+/g);
		// if (faces != null) {
		// 	var $iconList = $("#face-list");
		// 	for (var i = 0; i < faces.length; i++) {
		// 		var name = faces[i];
		// 		var icon = $iconList.find('a[title="' + name + '"]').html();
		// 		content = content.replace('face[' + name + ']', icon)
		// 	}
		// }
		return content;
	}

	var createGroup = function(param) {
		socket.send(2006, {
			memberIds: param.mers,
			groupName: param.name,
			admin: user.id
		}, function(result) {
			console.log(result);
		}, 4006)
	}

	var uuid = function() {
		return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
			var r = Math.random() * 16 | 0,
				v = c == 'x' ? r : (r & 0x3 | 0x8);
			return v.toString(16);
		});
	}



	return {
		init: init,
		initUserList: initUserList,
		initFriendsList: initFriendsList,
		sendMsg: sendMsg,
		createGroup: createGroup,
	}

})();
chat.init()
